package org.meb.conquest.web.services;

import java.io.Serializable;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.meb.conquest.web.AutoCompleteCache;
import org.meb.conquest.web.AutoCompleteItem;

// @FacesConverter(value = "autoCompleteItem", forClass =
// AutoCompleteItem.class)
@Named
@ViewScoped
public class AutoCompleteItemConverter implements Converter, Serializable {

	private static final long serialVersionUID = -2572426106463408850L;

	@Inject
	private AutoCompleteCache cache;

	public Object getAsObject(FacesContext facesContext, UIComponent component, String id) {
		if (StringUtils.isBlank(id)) {
			return null;
		} else {
			return cache.get(id).getTarget();
		}
	}

	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return AutoCompleteItem.createUniqueId(value);
		}
	}
}